extends Control

@onready var pos: Control = $Pos
@onready var point: TextureRect = $Pos/Point
@onready var length: Label = $Pos/Length
@onready var fly: Control = $Fly
@onready var fly_point: TextureRect = $Fly/Point

var current_scene : Node2D

func _ready() -> void:
	current_scene = get_tree().current_scene
	current_scene.ball_rotation.connect(_set_fly_rotation)
	current_scene.ball_emit.connect(_on_ball_emit_event)
	fly.hide()

func _process(delta: float) -> void:
	var current_cole = current_scene.current_cole
	var camera : Camera2D = current_scene.camera
	var ball = current_scene.ball
	var dir = current_cole.global_position - ball.global_position
	
	var viewport_rect = camera.get_viewport_rect()
	viewport_rect.size /= camera.zoom
	viewport_rect.size *= 0.5
	if viewport_rect.has_point(abs(camera.to_local(current_cole.global_position))) :
		pos.hide()
	elif current_scene.is_camera_follow :
		pos.hide()
	else :
		pos.show()
	
	pos.position = dir.normalized() * (size.y / 2.0 - 64.0) + (size / 2.0) - (point.size / 2.0)
	point.rotation_degrees = rad_to_deg(atan2(dir.y,dir.x))

func _set_fly_rotation(target : Vector2) :
	fly.show()
	fly.position = -target + (size / 2.0) - (fly_point.size / 2.0)
	fly_point.rotation_degrees = rad_to_deg(atan2(target.y,target.x)) - 180.0

func _on_ball_emit_event(dir : Vector2) :
	fly.hide()
